package com.xncoding.wechat.utils;


import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;
import java.util.*;

@Component
public class SignatureUtil {

    /**
     * 生成SHA1签名
     */
    public String generateSHA1Sign(Map<String, String> params, String appKey) {
        // 按照字母顺序排序
        List<String> keys = new ArrayList<>(params.keySet());
        Collections.sort(keys);

        // 构建签名字符串
        StringBuilder signBuilder = new StringBuilder();
        for (String key : keys) {
            String value = params.get(key);
            if (value != null && !value.isEmpty()) {
                signBuilder.append(key).append("=").append(value).append("&");
            }
        }

        // 添加appkey
        signBuilder.append("appkey=").append(appKey);

        // SHA1加密
        return DigestUtils.sha1Hex(signBuilder.toString());
    }

    /**
     * 验证签名
     */
    public boolean verifySignature(Map<String, String> params, String appKey, String paysign) {
        String generatedSign = generateSHA1Sign(params, appKey);
        return generatedSign.equals(paysign);
    }

    /**
     * 构建跳转URL参数
     */
    public String buildRedirectUrlParams(Map<String, String> params) {
        List<String> paramList = new ArrayList<>();
        for (Map.Entry<String, String> entry : params.entrySet()) {
            paramList.add(entry.getKey() + "=" + entry.getValue());
        }
        return String.join("&", paramList);
    }
}
